package db

import (
	"fmt"
	"log"
	"os"
	"ticket/internal/db/model"
	"time"

	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

var GormDB *gorm.DB

func InitDB(prefix string) {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             time.Second,
			LogLevel:                  logger.Error, // 只打印错误SQL，设置为Silent禁用SQL语句输出
			IgnoreRecordNotFoundError: true,
			Colorful:                  true,
		})

	option := gorm.Config{
		Logger:                 newLogger,
		PrepareStmt:            true,
		SkipDefaultTransaction: true,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   prefix,
			SingularTable: true,
		},
	}

	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		viper.GetString("db.user"),
		viper.GetString("db.password"),
		viper.GetString("db.host"),
		viper.GetInt("db.port"),
		viper.GetString("db.name"),
	)

	zap.S().Info("mysql dsn: ", dsn)
	db, err := gorm.Open(mysql.Open(dsn), &option)
	if err != nil {
		zap.S().Fatalf("MySQL数据库连接失败:%s:%d", viper.GetString("db.host"), viper.GetInt("db.port"))
	}

	db.AutoMigrate(&model.User{}, &model.Team{}, &model.Task{}, &model.TaskLog{}, &model.Project{}, &model.Role{})
	GormDB = db

	user := &model.User{
		UserName: "admin@qq.com",
		NickName: "管理员",
		Password: "123456",
		Email:    "admin@qq.com",
		IsSuper:  1,
	}
	user.Create(GormDB)
}
